package com.sbtr.security.controller;


import com.google.code.kaptcha.Producer;
import com.sbtr.security.common.constant.Constant;
import com.sbtr.security.common.exception.CaptchaException;
import com.sbtr.security.common.security.LoginFailureHandler;
import com.sbtr.security.entity.R;
import com.sbtr.security.util.RedisUtil;
import com.sbtr.security.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 验证码Controller控制器
 */
@RestController
public class CaptchaController {

    @Autowired
    private Producer producer;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    LoginFailureHandler loginFailureHandler;

    @GetMapping("/captcha")
    public R captcha() throws IOException {
        String key = UUID.randomUUID().toString(); // 生成随机唯一key
        String code = producer.createText();

        System.out.println("code=" + code);

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());

        redisUtil.hset(Constant.CAPTCHA_KEY, key, code, 60 * 5);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("base64Img", base64Img);
        resultMap.put("uuid", key);
        return R.ok(resultMap);
    }

//    @PostMapping("/login")
//    public R captcha(HttpServletRequest r, HttpServletResponse p) throws IOException, ServletException {
//        try{
//            // 校验验证码
//            validate(r);
//        } catch (CaptchaException e) {
//
//            // 交给认证失败处理器
//            loginFailureHandler.onAuthenticationFailure(r, p, e);
//        }
//        return R.ok();
//    }
    // 校验验证码逻辑
    private void validate(HttpServletRequest httpServletRequest) {

        String code = httpServletRequest.getParameter("code");
        String key = httpServletRequest.getParameter("uuid");

        if (StringUtil.isEmpty(code) || StringUtil.isEmpty(key)) {
            throw new CaptchaException("验证码错误");
        }

        if (!code.equals(redisUtil.hget(Constant.CAPTCHA_KEY, key))) {
            throw new CaptchaException("验证码错误");
        }

    }

}
